package org.jeecg.modules.basicWarehouse.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.rms.util.RMSTemplate;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basicWarehouse.entity.ConnectionPosition;
import org.jeecg.modules.basicWarehouse.entity.BasicWarehouse;
import org.jeecg.modules.basicWarehouse.vo.BasicWarehousePage;
import org.jeecg.modules.basicWarehouse.service.IBasicWarehouseService;
import org.jeecg.modules.basicWarehouse.service.IConnectionPositionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 仓库
 * @Author: jeecg-boot
 * @Date:   2025-03-12
 * @Version: V1.0
 */
@Api(tags="仓库")
@RestController
@RequestMapping("/basicWarehouse/basicWarehouse")
@Slf4j
public class BasicWarehouseController {
	@Autowired
	private IBasicWarehouseService basicWarehouseService;
	@Autowired
	private IConnectionPositionService connectionPositionService;

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private RMSTemplate rmsTemplate;
	
	/**
	 * 分页列表查询
	 *
	 * @param basicWarehouse
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "仓库-分页列表查询")
	@ApiOperation(value="仓库-分页列表查询", notes="仓库-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(BasicWarehouse basicWarehouse,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BasicWarehouse> queryWrapper = QueryGenerator.initQueryWrapper(basicWarehouse, req.getParameterMap());
		Page<BasicWarehouse> page = new Page<BasicWarehouse>(pageNo, pageSize);
		IPage<BasicWarehouse> pageList = basicWarehouseService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @AutoLog(value = "接驳位-获取全部接驳位")
	 @ApiOperation(value="接驳位-获取全部接驳位", notes="接驳位-获取全部接驳位")
	 @GetMapping(value = "/getConnection")
	 public Result<?> getConnection() {
		 // 获取所有记录
		 List<Map<String, Object>> list = connectionPositionService.listMaps();

		 // 使用stream API根据warehouseName进行分组
		 Map<String, List<Map<String, Object>>> groupedByWarehouseName = list.stream()
				 .collect(Collectors.groupingBy(m -> (String) m.get("warehouse_name")));

		 // 构建返回结果
		 List<Map<String, Object>> result = groupedByWarehouseName.entrySet().stream()
				 .map(entry -> {
					 Map<String, Object> map = new HashMap<>();
					 map.put("warehouse_name", entry.getKey());
					 map.put("data", entry.getValue());
					 return map;
				 })
				 .collect(Collectors.toList());
		 List<Map<String, Object>> maps = connectionPositionService.updateReadyStatus(result);
		 return Result.OK(maps);
	 }

	 @AutoLog(value = "接驳位-接驳位准备就绪")
	 @ApiOperation(value="接驳位-接驳位准备就绪", notes="接驳位-接驳位准备就绪")
	 @PostMapping(value = "/cellReady")
	 public Result<?> cellReady(@RequestBody JSONObject jsonObject) {
		 try {
			 // 检查传入的对象是否为空
			 if (jsonObject == null || jsonObject.getString("cell_code") == null) {
				 return Result.error("数据校验失败");
			 }
			 String cellCode = jsonObject.getString("cell_code");
			 String key = "cellCode:" + cellCode;
			 // 获取当前状态并切换
			 if (redisUtil.hasKey(key)) {
				 Object currentValue = redisUtil.get(key);
				 if (currentValue instanceof Integer) {
					 int currentState = (Integer) currentValue;
					 redisUtil.set(key, currentState == 1 ? 0 : 1);
				 } else {
					 redisUtil.set(key, 1);
				 }
			 } else {
				 redisUtil.set(key, 1);
			 }
			 return Result.OK("操作成功");
		 } catch (Exception e) {
			 // 记录异常并返回错误结果
			 log.error(e.getMessage(), e);
			 return Result.error("服务器错误");
		 }
	 }

	 @AutoLog(value = "接驳位-刷新准备状态")
	 @ApiOperation(value="接驳位-刷新准备状态", notes="接驳位-刷新准备状态")
	 @PostMapping(value = "/refresh")
	 public Result<?> refresh(@RequestBody List<Map<String, Object>> list) {
		 List<Map<String, Object>> maps = connectionPositionService.updateReadyStatus(list);
		 return Result.OK(maps);
	 }

	 @AutoLog(value = "接驳位-呼叫货架")
	 @ApiOperation(value="接驳位-呼叫货架", notes="接驳位-呼叫货架")
	 @PostMapping(value = "/callShelf")
	 public Result<?> callShelf(@RequestBody JSONObject jsonObject) {
		 String cellCode = jsonObject.getString("cell_code");//接驳位单元格
		 String giveCell = jsonObject.getString("give_cell");//送至单元格
		 String getCell = jsonObject.getString("get_cell");//取回单元格
		 if (StringUtils.isEmpty(cellCode) || StringUtils.isEmpty(giveCell) || StringUtils.isEmpty(getCell)) {
			 return Result.error("请求参数不能为空");
		 }
		 JSONObject cellCodePoint = rmsTemplate.cellPoint(cellCode);
		 String cellCodeShelf = checkShelfOfCell(cellCodePoint);
		 if(StringUtils.isEmpty(cellCodeShelf)){
			 return Result.error("【接驳点位】无货架");
		 }
		 JSONObject giveCellPoint = rmsTemplate.cellPoint(giveCell);
		 String giveCellShelf = checkShelfOfCell(giveCellPoint);
		 if (!StringUtils.isEmpty(giveCellShelf)){
			 return Result.error("【送至点位】有货架");
		 }
		 JSONObject getCellPoint = rmsTemplate.cellPoint(getCell);
		 String getCellShelf = checkShelfOfCell(getCellPoint);
		 if (StringUtils.isEmpty(getCellShelf)){
			 return Result.error("【取回点位】无货架");
		 }
		 JSONObject res = rmsTemplate.deliverShelf(cellCodeShelf, giveCell);
		 if (res == null || !res.containsKey("response")) {
			 return Result.error("交付货架失败");
		 }
		 JSONObject response = res.getJSONObject("response");
		 if (response == null || !response.containsKey("body")) {
			 return Result.error("交付货架失败");
		 }
		 JSONObject body = response.getJSONObject("body");
		 if (body == null || !body.containsKey("taskId")) {
			 return Result.error("交付货架失败");
		 }
		 String taskId = body.getString("taskId");
		 redisUtil.set(taskId, getCellShelf + "+" + cellCode);
		 String key = "cellCode:" + cellCode;
		 redisUtil.set(key, 0);
		 return Result.OK();
	 }

	 private String checkShelfOfCell(JSONObject jsonObject) {
		 if (jsonObject == null || !jsonObject.containsKey("response")) {
			 return null;
		 }
		 JSONObject response = jsonObject.getJSONObject("response");
		 if (response == null || !response.containsKey("body")) {
			 return null;
		 }
		 JSONObject body = response.getJSONObject("body");
		 if (body == null || !body.containsKey("cells") || body.getJSONArray("cells").isEmpty()) {
			 return null;
		 }
		 JSONObject cell = body.getJSONArray("cells").getJSONObject(0);
		 Set<String> strings = cell.keySet();
		 if (strings.contains("occupiedShelfCode")) {
			 return cell.getString("occupiedShelfCode");
		 } else {
			 return "";
		 }
	 }

	 @AutoLog(value = "RMS-回调")
	 @ApiOperation(value="RMS-回调", notes="RMS-回调")
	 @PostMapping(value = "/m/callBack")
	 public Result<?> callBack(@RequestBody JSONObject jsonObject) {
		 log.info("jsonObject: {}", jsonObject);
		 JSONObject request = jsonObject.getJSONObject("request");
		 if (request != null) {
			 JSONObject body = request.getJSONObject("body");
			 if (body != null) {
				 String taskStatus = body.getString("taskStatus");
				 if ("COMPLETED".equals(taskStatus)) {
					 String taskId = body.getString("taskId");
					 if (redisUtil.hasKey(taskId)) {
						 String o = (String) redisUtil.get(taskId);
						 String[] split = o.split("\\+");
						 if (split.length == 2) {
							 rmsTemplate.deliverShelf(split[0], split[1]);
							 redisUtil.del(taskId);
						 } else {
							 log.warn("任务ID对应的值格式不正确: {}", o);
						 }
					 } else {
						 log.warn("任务ID {} 不存在", taskId);
					 }
				 }
			 }
		 }
		 return Result.OK();
	 }
	
	/**s
	 *   添加
	 *
	 * @param basicWarehousePage
	 * @return
	 */
	@AutoLog(value = "仓库-添加")
	@ApiOperation(value="仓库-添加", notes="仓库-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody BasicWarehousePage basicWarehousePage) {
		BasicWarehouse basicWarehouse = new BasicWarehouse();
		BeanUtils.copyProperties(basicWarehousePage, basicWarehouse);
		basicWarehouseService.saveMain(basicWarehouse, basicWarehousePage.getConnectionPositionList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param basicWarehousePage
	 * @return
	 */
	@AutoLog(value = "仓库-编辑")
	@ApiOperation(value="仓库-编辑", notes="仓库-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody BasicWarehousePage basicWarehousePage) {
		BasicWarehouse basicWarehouse = new BasicWarehouse();
		BeanUtils.copyProperties(basicWarehousePage, basicWarehouse);
		BasicWarehouse basicWarehouseEntity = basicWarehouseService.getById(basicWarehouse.getId());
		if(basicWarehouseEntity==null) {
			return Result.error("未找到对应数据");
		}
		basicWarehouseService.updateMain(basicWarehouse, basicWarehousePage.getConnectionPositionList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "仓库-通过id删除")
	@ApiOperation(value="仓库-通过id删除", notes="仓库-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		basicWarehouseService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "仓库-批量删除")
	@ApiOperation(value="仓库-批量删除", notes="仓库-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.basicWarehouseService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "仓库-通过id查询")
	@ApiOperation(value="仓库-通过id查询", notes="仓库-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BasicWarehouse basicWarehouse = basicWarehouseService.getById(id);
		if(basicWarehouse==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(basicWarehouse);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "接驳位通过主表ID查询")
	@ApiOperation(value="接驳位主表ID查询", notes="接驳位-通主表ID查询")
	@GetMapping(value = "/queryConnectionPositionByMainId")
	public Result<?> queryConnectionPositionListByMainId(@RequestParam(name="id",required=true) String id) {
		List<ConnectionPosition> connectionPositionList = connectionPositionService.selectByMainId(id);
		return Result.OK(connectionPositionList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param basicWarehouse
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BasicWarehouse basicWarehouse) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<BasicWarehouse> queryWrapper = QueryGenerator.initQueryWrapper(basicWarehouse, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<BasicWarehouse> queryList = basicWarehouseService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<BasicWarehouse> basicWarehouseList = new ArrayList<BasicWarehouse>();
      if(oConvertUtils.isEmpty(selections)) {
          basicWarehouseList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          basicWarehouseList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<BasicWarehousePage> pageList = new ArrayList<BasicWarehousePage>();
      for (BasicWarehouse main : basicWarehouseList) {
          BasicWarehousePage vo = new BasicWarehousePage();
          BeanUtils.copyProperties(main, vo);
          List<ConnectionPosition> connectionPositionList = connectionPositionService.selectByMainId(main.getId());
          vo.setConnectionPositionList(connectionPositionList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "仓库列表");
      mv.addObject(NormalExcelConstants.CLASS, BasicWarehousePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("仓库数据", "导出人:"+sysUser.getRealname(), "仓库"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<BasicWarehousePage> list = ExcelImportUtil.importExcel(file.getInputStream(), BasicWarehousePage.class, params);
              for (BasicWarehousePage page : list) {
                  BasicWarehouse po = new BasicWarehouse();
                  BeanUtils.copyProperties(page, po);
                  basicWarehouseService.saveMain(po, page.getConnectionPositionList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
